package com.ashafa.server;

import java.io.File;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.ajp.Ajp13SocketConnector;
import org.mortbay.jetty.handler.ResourceHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.thread.QueuedThreadPool;

import org.apache.log4j.*;

public class ServerStart {
	
	private static final Logger logger = Logger.getLogger(ServerStart.class.getName()); 

	
	public static void main(String[] args) throws Exception	{

		BasicConfigurator.configure();
		System.setProperty("file.encoding", "UTF-8");
				
		Properties properties = new Properties();
	    try {
	    	properties.load(new FileInputStream(System.getProperty("user.dir") + "/server.properties"));
	    } catch (IOException e) {
	    	logger.warn("'server.properties' not found in installation directory. Using default server properties.");
	    }
	    
	   
	    int port = 8080;
	    String contexts = "./contexts"; 
		String resourceBase = "./web-files/static";
		
		Server server;
		
		if(properties.get("server.port")!=null)
			port = Integer.parseInt((String)properties.get("server.port"));
		
		if(properties.get("server.static")!=null)
			resourceBase = (String)properties.get("server.static");
		
		if(properties.get("server.contexts")!=null)
			contexts = (String)properties.get("server.contexts");
		
		server = new Server();
		
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMaxThreads(100);
		server.setThreadPool(threadPool);
		
		File dir = new File(contexts);
		String [] list = dir.list();
		
		for (int i = 0; i < list.length; i++)
		{
			try
			{
				if((!list[i].equals("static") && !list[i].equals("admin")) && new File(contexts + "/"+list[i]).isDirectory() && new File(contexts + "/"+list[i] + "/urls.json").exists())
				{
					Context context = new Context(server,"/"+list[i], Context.SESSIONS);
			 		if(properties.get("server.clear-cookie-path") != null && ((String)properties.get("clear-cookie-path")).equals("true"))
			 		{
			 			context.getSessionHandler().getSessionManager().setSessionPath("/");
			 		}
			 		context.addServlet(new ServletHolder(new Servlet(contexts, context)), "/*");
			 		context.setErrorHandler(new CustomErrorHandler(true, true));
			 		
			 	}
				
			} catch(Exception e) {
				logger.error(e);
			}
		}    
		      
		if(properties.get("server.protocol") != null && ((String)properties.get("server.protocol")).equals("ajp"))
		{
			Connector ajpConnector = new Ajp13SocketConnector();
			ajpConnector.setPort(port);
			server.setConnectors(new Connector[] {ajpConnector});
			
		} else {
		   
			Connector connector = new SelectChannelConnector();
		    connector.setPort(port);
		    connector.setMaxIdleTime(30000);
		    server.setConnectors(new Connector[]{connector});
			
			ResourceHandler resourceHandler = new ResourceHandler();
			resourceHandler.setResourceBase(resourceBase);
			Context staticContext = new Context(server,"/" + resourceBase.split("/")[resourceBase.split("/").length - 1], 0);
			staticContext.setHandler(resourceHandler);
			staticContext.setErrorHandler(new CustomErrorHandler(false, false));
			
		}
				
		Context rootContext = new Context(server,"/", 0);
		rootContext.setHandler(new CustomDefaultHandler());
		rootContext.setErrorHandler(new CustomErrorHandler(false, false));
			
		server.start();
		server.join();
	}
}
